package com.zyfdroid.backupftpserver;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

import com.zyfdroid.backupftpserver.ftplets.AnonymousUserManager;
import com.zyfdroid.backupftpserver.ftplets.MyFtpFileSystemFactory;

import org.apache.ftpserver.ConnectionConfig;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.impl.DefaultConnectionConfig;
import org.apache.ftpserver.listener.ListenerFactory;

public class ServerService extends Service {

    public static FtpServer fs;
    public ServerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        FtpServer server = null;

        FtpServerFactory fsf = new FtpServerFactory();
        ListenerFactory lf = new ListenerFactory();
        lf.setPort(8421);
        fsf.addListener("default", lf.createListener());
        fsf.setFileSystem(new MyFtpFileSystemFactory(getPackageManager(),this));
        fsf.setUserManager(new AnonymousUserManager());

        server = fsf.createServer();

        try {
            server.start();
            Toast.makeText(this, "服务器已开启", Toast.LENGTH_SHORT).show();
            fs = server;
        } catch (FtpException e) {
            e.printStackTrace();
            Toast.makeText(this, "服务器开启失败："+e.getMessage(), Toast.LENGTH_SHORT).show();
            server.stop();
        }
        startForeground(NotificationUtils.notificationId,NotificationUtils.postNoification(this,"FTP服务器正在运行... \r\n点击打开界面","FTP文件同步"));
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        FtpServer server = fs;
        fs = null;
        server.stop();
        stopForeground(true);
        Toast.makeText(getApplicationContext(), "服务器已关闭", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }
}